package game

import (
	"errors"
	"github.com/gorilla/websocket"
	"gogogo-server/gameserver/model"
	"sync"
)

// Player 结构体代表一个玩家
type PlayerConn struct {
	Player *model.Player
	Conn   *websocket.Conn
	// 其他玩家相关的字段...
}

// Room 结构体代表一个游戏房间
type Room struct {
	ID      int
	Players map[uint]*PlayerConn
	Mutex   sync.Mutex
	// 其他房间相关的字段，如游戏状态...
}

var RoomsMap = make(map[int]*Room)
var RoomsMutex = &sync.Mutex{}

// AddRoom - 向全局列表添加一个新房间
func AddRoom(room *Room) {
	RoomsMutex.Lock()
	defer RoomsMutex.Unlock()
	RoomsMap[room.ID] = room
}

// GetRoom - 从全局列表中获取一个房间
func GetRoom(id int) (*Room, bool) {
	RoomsMutex.Lock()
	defer RoomsMutex.Unlock()
	room, exists := RoomsMap[id]
	return room, exists
}

// NewRoom 创建并返回一个新的游戏房间
func NewRoom(id int) *Room {
	return &Room{
		ID:      id,
		Players: make(map[uint]*PlayerConn),
	}
}

// AddPlayer 向房间添加一个玩家
func (r *Room) AddPlayer(playerConn *PlayerConn) error {
	r.Mutex.Lock()
	defer r.Mutex.Unlock()

	if _, exists := r.Players[playerConn.Player.ID]; exists {
		return errors.New("player already exists in the room")
	}

	r.Players[playerConn.Player.ID] = playerConn
	return nil
}

// RemovePlayer 从房间中移除一个玩家
func (r *Room) RemovePlayer(playerID uint) {
	r.Mutex.Lock()
	defer r.Mutex.Unlock()

	delete(r.Players, playerID)
}

// GetPlayer 返回房间中的玩家
func (r *Room) GetPlayer(playerID uint) (*PlayerConn, bool) {
	r.Mutex.Lock()
	defer r.Mutex.Unlock()

	player, exists := r.Players[playerID]
	return player, exists
}

// BroadcastMessage 向房间内的所有玩家广播消息
func (r *Room) BroadcastMessage(message string) {
	// 实现向所有玩家广播消息的逻辑
	// 这可能涉及到与 WebSocket 连接的交互
}
